<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>水平菜单</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .container {
        width: 1000px;
        margin: 50px auto;
      }

      .menu {
        list-style: none;
        display: flex;
        line-height: 48px;
        border-bottom: 1px solid rgb(5, 5, 5, 0.1);
      }

      .menu-item {
        margin: 0 16px;
        position: relative;
      }
      .menu-item:hover{
        cursor: pointer;
        border-bottom: 2px solid #1677ff;
      }
      .menu-item-active {
        color: #1677ff;
        border-bottom: 2px solid #1677ff;
      }
      .sub-menu{
        list-style: none;
        display: none;
        border: 1px solid rgb(5, 5, 5, 0.1);
        border-radius: 8px;
        position: absolute;
        z-index: 1000;
        min-width: 120px;
      }
      .menu-item:hover .sub-menu{
        display: block;
      }
      .sub-menu-item{
        border-radius: 8px;
        text-align: center;
        line-height: 36px;
      }
      .sub-menu-item:hover{
        background-color: rgb(5, 5, 5, 0.1);
      }
    </style>
  </head>

  <body>
    <div class="container">
      <ul class="menu">
        <li class="menu-item menu-item-active"><a>一级菜单项-1</a></li>
        <li class="menu-item"><a>一级菜单项-2</a></li>
        <li class="menu-item">
            <a>一级菜单项-3</a>
            <ul class = "sub-menu">
                <li class = "sub-menu-item"><span>  二级菜单项-1</span></li>
                <li class = "sub-menu-item"><span>  二级菜单项-2</span></li>
            </ul>
        </li>
        <li class="menu-item"><a>一级菜单项-4</a></li>
      </ul>
    </div>
    <script>
      const menu = document.querySelector(".menu");
      menu.addEventListener("click",(event) =>{
        const menuItem = event.target.closest(".menu-item");
        if(!menuItem || !menu.contains(menuItem))return;
        const active = menu.querySelector(".menu-item-active");
        active.classList.remove("menu-item-active");
        menuItem.classList.add("menu-item-active");
      });
    </script>
  </body>
</html>
